package com.zd.controller;

import com.zd.entity.Comments;
import com.zd.entity.News;
import com.zd.entity.Topic;
import com.zd.service.CommentsService;
import com.zd.service.NewsService;
import com.zd.service.TopicService;
import com.zd.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private TopicService topicService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private Environment environment;
    @Autowired
    private CommentsService commentsService;

    @GetMapping("/")
    public String index(Model model){
        //List<News> newsList = newsService.queryAllNews();

        List<Topic> topics=topicService.queryAllTopics();
        String guonei=environment.getProperty("guonei");
        String guoji=environment.getProperty("guoji");
        String yule=environment.getProperty("yule");
        List<News> newsList1 = newsService.queryNewsByTname(guonei);//国内
        List<News> newsList2 = newsService.queryNewsByTname(guoji);//国际
        List<News> newsList3 = newsService.queryNewsByTname(yule);//娱乐
        model.addAttribute("topics",topics);
        //model.addAttribute("newsList",newsList);
        model.addAttribute("newsList1",newsList1);
        model.addAttribute("newsList2",newsList2);
        model.addAttribute("newsList3",newsList3);
        return "index";
    }

    @GetMapping("/index/topicnews/{tid}")
    @ResponseBody
    public Object topicNews(@PathVariable("tid") Long tid){
        List<News> topicNewsList = newsService.queryNewsByTid(tid);
        return topicNewsList;
    }

    @GetMapping("/index/readnews/{nid}")
    public String readNews(@PathVariable("nid") Long nid,Model model){
        News news = newsService.queryNewsByNid(nid);
        model.addAttribute("news",news);
        return "readnews";
    }

    @PostMapping("/index/addComments")
    public String addComments(Comments comments){
        commentsService.publishCommments(comments);
        return "redirect:/index/readnews/"+comments.getCnid();
    }

    @GetMapping("/index/pagenews")
    @ResponseBody
    public Object pageNews(@RequestParam(value = "pageNo",required = false) Integer pageNo){
        if(pageNo == null | pageNo<1){
            pageNo=1;
        }
        PageUtil page = newsService.queryNewsByPage(pageNo);
        return page;
    }

}
